<template>
  <div class="attribute-wrap">
    <el-row :gutter="20">
      <!--属性类别数据-->
      <el-col :span="3" :xs="24">
        <div class="head-container">
          <el-tree
            ref="atTree"
            :data="atTreeData"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            node-key="nodeKey"
            highlight-current
            :default-expanded-keys="['all']"
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <i :class="{'el-icon-folder': !node.isLeaf, 'el-icon-document': node.isLeaf}" />
              {{ data.label }}
            </span>
          </el-tree>
        </div>
      </el-col>

      <!--用户数据-->
      <el-col :span="21" :xs="24">
        <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true">
          <el-form-item label="代码" prop="basicCode">
            <el-input
              v-model="queryParams.basicCode"
              placeholder="请输入代码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="名称" prop="basicName">
            <el-input
              v-model="queryParams.basicName"
              placeholder="请输入名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="queryParams.remarks"
              placeholder="请输入备注"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-show="this.modelId==null"
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-show="this.modelId==null"
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除</el-button>
          </el-col>

          <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
        </el-row>

        <el-table ref="tableRef"
          :class="{'single-select' : singleSelect}"
          v-loading="loading" :data="fieldList" style="border: 1px solid #e6ebf5;" border @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="代码" width="auto" align="center" prop="basicCode" sortable :show-overflow-tooltip="true" />
          <!--      <el-table-column label="最终代码" align="center" prop="finalBasicCode" sortable :show-overflow-tooltip="true"/>-->
          <el-table-column label="名称" width="auto" align="center" prop="basicName" sortable :show-overflow-tooltip="true" />
          <el-table-column label="数据类型" min-width="50%" width="auto" align="center" prop="basicJavaType" sortable :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.basicJavaType" :value="scope.row.basicJavaType" />
            </template>
          </el-table-column>
          <el-table-column label="页面元素" min-width="50%" width="auto" align="center" prop="formTypeName" sortable :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.formtypename" :value="scope.row.formTypeName" />
            </template>
          </el-table-column>
          <el-table-column label="是否复杂属性" min-width="50%" width="auto" align="center" prop="dataExtend" sortable :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span v-if="scope.row.dataExtend == 'true'">是</span>
              <span v-else>否</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" width="auto" align="center" prop="remarks" sortable :show-overflow-tooltip="true" />

          <!-- 去掉关联模型 -->
          <!-- <el-table-column label="关联模型" min-width="110%" width="auto" align="center" prop="assTemplates" :show-overflow-tooltip="true" sortable /> -->
          <!--      <el-table-column label="排序" align="center" prop="sortNum" sortable/>-->
          <el-table-column v-if="this.modelId==null" label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                v-if="scope.row.dataExtend == 'true'"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="editComplex(scope.row)"
              >编辑复杂属性</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

      </el-col>
    </el-row>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" :close-on-click-modal="false" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">

        <el-row>
          <el-col :span="11">

            <el-form-item label="代码" prop="basicCode">
              <el-input v-if="form.basicCode == '_RESPONUSERNAME' || form.basicCode == '_EXECUTORNAME' || form.basicCode == '_CHECKUSERNAME' || form.basicCode == '_RESPONDEPTNAME'" v-model="form.basicCode" readonly maxlength="40" placeholder="请输入代码" />
              <el-input v-else v-model="form.basicCode" maxlength="40" placeholder="请输入代码" />
              <!--          <br/><font style="color: red">&nbsp;*数据通过模型转换时代码后缀相同属性可以匹配填充值。（例如：_b和a_b可以匹配）</font>-->
            </el-form-item>

          </el-col>
          <el-col :span="11">

            <el-form-item label="名称" prop="basicName">
              <el-input v-model="form.basicName" placeholder="请输入名称" />
            </el-form-item>

          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">

            <el-form-item label="属性类别1" prop="attributeType">

              <treeselect
                v-model="form.attributeType"
                style="width: 271px;"
                :options="atTreeData1"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="请选择属性类别"

                :disabled="atDisabled"
              />
            </el-form-item>

          </el-col>
          <el-col :span="11">

            <el-form-item label="排序" prop="sortNum">
              <el-input-number v-model="form.sortNum" placeholder="请输入排序" style="width:100%;" />
            </el-form-item>

          </el-col>
        </el-row>

        <el-row>
          <el-col>

            <el-form-item label="数据类型" prop="dataType">

              <div style="border: 1px solid #e6ebf5;width: 90%;">
                <div style="margin-left:30px;margin-top:20px;">
                  <span>文本：</span>
                  <el-radio v-model="dataType" style="margin-left:10px;" label="text_1" @change="setFormData">普通文本</el-radio>
                  <el-radio v-model="dataType" label="text_2" @change="setFormData">多行文本</el-radio>
                  <el-radio v-model="dataType" label="text_3" @change="setFormData">富文本</el-radio>

                </div>

                <div style="margin-left:30px;margin-top:10px;">
                  <span>数字：</span>
                  <el-radio v-model="dataType" style="margin-left:10px;" label="num_1" @change="setFormData">整数</el-radio>
                  <el-radio v-model="dataType" label="num_2" @change="setFormData">小数</el-radio>
                </div>

                <div style="margin-left:30px;margin-top:10px;">
                  <span>日期：</span>
                  <el-radio v-model="dataType" style="margin-left:10px;" label="date_1" @change="setFormData">日期</el-radio>
                  <el-radio v-model="dataType" label="date_2" @change="setFormData">日期时间</el-radio>
                </div>

                <div style="margin-left:30px;margin-top:10px;">
                  <span>字典：</span>
                  <el-radio v-model="dataType" style="margin-left:10px;" label="dic_1" @change="setFormData">下拉单选</el-radio>
                  <el-radio v-model="dataType" label="dic_2" @change="setFormData">下拉多选</el-radio>
                  <el-radio v-model="dataType" label="dic_3" @change="setFormData">树单选</el-radio>
                  <el-radio v-model="dataType" label="dic_4" @change="setFormData">树多选</el-radio>
                  <el-radio v-model="dataType" label="dic_6" @change="setFormData">单选(radio)</el-radio>
                  <el-radio v-model="dataType" label="dic_7" @change="setFormData"> 多选(checkbox)</el-radio>

                </div>

                <div style="margin-left:30px;margin-top:10px;">
                  <span>附件：</span>
                  <el-radio v-model="dataType" style="margin-left:10px;" label="file_1" @change="setFormData">普通附件</el-radio>
                  <el-radio v-model="dataType" label="upload_folder" @change="setFormData">文件夹上传</el-radio>

                </div>

                <div style="margin-left:30px;margin-top:10px;margin-bottom:20px;">
                  <span>表格：</span>
                  <el-radio v-model="dataType" style="margin-left:10px;" label="table_1" @change="setFormData">表格(复杂属性)</el-radio>
                </div>
              </div>

            </el-form-item>

          </el-col>
        </el-row>

        <el-row>

          <el-col :span="11">
            <!-- TODO 文件夹上传可以隐藏此选项 -->
            <el-form-item v-if="this.form.dataExtend == 'false'" label="是否必填">
              <el-switch v-model="form.jsRequired" active-value="1" inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item v-if="this.form.dataExtend == 'false'" label="是否只读">
              <el-switch v-model="form.isReadOnly" active-value="1" inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item v-if="form.dataExtend == 'false'&&(form.formTypeName == 'upload')" label="上传类型">
              <el-select v-model="form.uploadtypeId" clearable placeholder="请选择上传类型" style="width: 80%;">
                <el-option
                  v-for="upload in uploadTypeList"
                  :key="upload.id"
                  :label="upload.name"
                  :value="upload.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="form.remarks" placeholder="请输入名称" style="width: 90%;"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>

            <el-form-item
              v-if=" form.dataExtend == 'false'&&(
                form.formTypeName == 'selectsingle'
                ||form.formTypeName == 'selectmulti'
                ||form.formTypeName == 'selectztree'
                ||form.formTypeName == 'selectztreemulti'
                ||form.formTypeName == 'selectztreecustomcheck'
                ||form.formTypeName == 'radio'
                ||form.formTypeName == 'checkbox'
              )"

              label="字典"
            >
              <el-select v-model="form.formDictType" clearable style="width: 90%;">
                <el-option
                  key=""
                  label="请选择"
                  value=""
                />
                <el-option
                  v-for="dict in dictList"
                  :key="dict.dictType"
                  :label="dict.dictName"
                  :value="dict.dictType"
                />
              </el-select>
            </el-form-item>

          </el-col>
        </el-row>

        <el-row>
          <el-col>

            <el-form-item
              v-if=" form.dataExtend == 'false'&&(
                form.formTypeName == 'selectsingle'
                ||form.formTypeName == 'selectmulti'
                ||form.formTypeName == 'selectztree'
                ||form.formTypeName == 'selectztreemulti'
                ||form.formTypeName == 'selectztreecustomcheck'
                ||form.formTypeName == 'radio'
                ||form.formTypeName == 'checkbox'
              )"

              label="选项值(逗号分割)"
            >
              <el-input v-model="form.defaultValue" placeholder="请输入选项值(逗号分割)" style="width: 90%;" />
            </el-form-item>

          </el-col>
        </el-row>

        <el-row>
          <el-col>

            <el-form-item
              v-if=" form.dataExtend == 'false'&&(
                form.formTypeName == 'selectsingle'
                ||form.formTypeName == 'selectmulti'
                ||form.formTypeName == 'selectztree'
                ||form.formTypeName == 'selectztreemulti'
                ||form.formTypeName == 'selectztreecustomcheck'
                ||form.formTypeName == 'radio'
                ||form.formTypeName == 'checkbox'
              )"
              label="联动父级字段"
            >
              <el-select v-model="form.parentLinkageId" clearable style="width: 90%;">
                <el-option
                  key=""
                  label="请选择"
                  value=""
                />
                <el-option
                  v-for="sl in selectList"
                  :key="sl.id"
                  :label="sl.basicName"
                  :value="sl.id"
                />
              </el-select>
            </el-form-item>

          </el-col>
        </el-row>

        <el-row>
          <el-col>

            <el-form-item v-if="this.form.dataExtend == 'true'" label="初始数据">
              <el-input v-model="form.initData" type="textarea" :rows="5" style="width: 90%;" />
            </el-form-item>

          </el-col>

        </el-row>

        <el-row>
          <el-col>

            <el-form-item v-if="this.form.dataExtend == 'true'" label="固定条目">
              <el-switch v-model="form.isAddDelFlag" active-value="1" inactive-value="0" />
            </el-form-item>

          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item v-if="this.form.dataExtend == 'true'" label="查看方式" prop="viewType">
              <el-radio v-model="form.viewType" label="0">列表显示</el-radio>
              <el-radio v-model="form.viewType" label="1">弹窗显示</el-radio>
            </el-form-item>

          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <edit-complex ref="editComplex" @getList="getList" />1
  </div>
</template>

<script>
import { listField, getField, delField, addField, updateField, basicCodeValid, getCodeSortNum, getAttributes, linkList, listSelectRefField } from '@/api/form/field'
import { listType as uploadTypeList } from '@/api/form/uploadtype'
import editComplex from './editComplex'
import { getDicts, getDictAll } from '@/api/system/dict/data'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: 'Field',
  components: { editComplex, Treeselect },
  props: {
    modelId: {
      type: String,
      required: false,
      default: null
    }, configFieldType: {
      type: String,
      required: false,
      default: null
    },
    singleSelect: {
      type: Boolean,
      default: false
    }
  },
  dicts: ['basic_java_type', 'form_type_name', 'data_extend', 'logic_yes_no', 'field_type', 'col_cal_type'],
  data() {
    var ValidCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('代码不能为空'))
      } else {
        basicCodeValid(value, this.id).then(data => {
          if (data == '1') {
            callback(new Error('已经存在该代码'))
          } else {
            callback()
          }
        })
      }
    }
    return {
      atDisabled: false,
      dcKeys: [],
      // 查询条件模型值
      queryModels: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      defaultProps1: {
        children: 'children',
        label: 'name'
      },
      atTreeData: [{
        'id': 'all',
        'label': '属性分类',
        'nodeKey': 'all',
        'children': []
      }],
      atTreeData1: [],
      dataType: 'text_1',
      checkedAxinessTypes: [],
      id: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      fieldList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      dictList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        basicCode: null,
        basicName: null,
        dataExtend: null,
        modelId: null,
        configFieldType: null,
        templateCode: null,
        remarks: null,
      },
      // 表单参数
      form: {
        refTableIdQte: null,
        configFieldTypeQte: null,
        qteModelIds: [],
        menuCheckStrictly: true
      },
      // 表单校验
      rules: {
        basicCode: [
          { required: true, validator: ValidCode, trigger: 'blur', message: '代码不能为空' }
        ], basicName: [
          { required: true, trigger: 'blur', message: '名称不能为空' }
        ], attributeType: [
          { required: true, trigger: 'blur', message: '属性类别不能为空' }
        ], sortNum: [
          { required: true, trigger: 'blur', message: '排序不能为空' }
        ], dataType: [
          { required: true, trigger: 'blur', message: '数据类型不能为空' }
        ], viewType: []
      },
      uploadTypeList: [],
      selectList: [],
      colCalFieldIds: [],
      componentList: [],
      simpleList: [],
      complexList: []
    }
  },
  created() {
    this.getList()
    this.getTreeData()
    uploadTypeList().then(data => {
      this.uploadTypeList = data
    })
  },
  mounted() {
    // this.$nextTick(() => {
    //   var _this = this
    //   window.addEventListener('resize', function() {
    //     _this.$layoutresize()
    //   })
    // })
  },
  methods: {
    // 树权限（父子联动）
    handleCheckedTreeConnect(value) {
      this.form.menuCheckStrictly = !!value
    },
    // 所有菜单节点数据
    getQteModelAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.qteModel.getCheckedKeys()
      // 半选中的菜单节点
      /*  let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);*/
      return checkedKeys
    },
    /** 折叠模型树形所有节点 */
    collapseAll() {
      if (this.$refs.qteModel) {
        const treeList = this.queryModels
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.qteModel.store.nodesMap[treeList[i].id].expanded = false
        }
      }
    },
    /** 转换业务类型、模型数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    // 节点单击事件
    handleNodeClick(data) {
      if (data.id == 'all') {
        this.queryParams.attributeType = null
      } else {
        this.queryParams.attributeType = data.id
      }
      this.handleQuery()
    },
    /* 获取属性类别树形数据**/
    getTreeData() {
      const cThis = this
      getDicts('field_type').then(response => {
        let treeData = []
        response.data.forEach(function(item, index) {
          const data = { 'id': item.dictValue, 'name': item.dictLabel, 'label': item.dictLabel, 'parentId': item.parentId, 'nodeKey': item.dictCode }
          treeData.push(data)
        })
        treeData = cThis.handleTree(treeData, 'nodeKey')
        this.atTreeData1 = treeData
        treeData.forEach(function(item, index) {
          const tree = { 'id': item.id, 'label': item.label, 'children': item.children, 'nodeKey': item.nodeKey }
          cThis.atTreeData[0].children.push(tree)
        })
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getData() {
      return this.fieldList.filter(item => this.ids.includes(item.id))
    },
    getSelectIds() {
      return this.ids
    },

    // 设置数据类型、页面元素
    setFormData() {
      const type = this.dataType
      // 重置查看方式表单校验
      this.rules.viewType = []
      if (type == 'text_1') { // 普通文本
        this.form.basicJavaType = 'string'
        this.form.dataExtend = 'false'
        this.form.formTypeName = 'input'
      } else if (type == 'text_2') { // 多行文本
        this.form.basicJavaType = 'string'
        this.form.dataExtend = 'false'
        this.form.formTypeName = 'textarea'
      } else if (type == 'text_3') { // 富文本
        this.form.basicJavaType = 'string'
        this.form.dataExtend = 'false'
        this.form.formTypeName = 'richtext'
      } else if (type == 'num_1') { // 整数
        this.form.basicJavaType = 'int'
        this.form.dataExtend = 'false'
        this.form.formTypeName = 'spinner'
      } else if (type == 'num_2') { // 小数
        this.form.basicJavaType = 'double'
        this.form.dataExtend = 'false'
        this.form.formTypeName = 'spinner'
      } else if (type == 'date_1') { // 日期
        this.form.basicJavaType = 'date'
        this.form.dataExtend = 'false'
        this.form.formTypeName = 'date'
      } else if (type == 'date_2') { // 日期时间
        this.form.basicJavaType = 'datetime'
        this.form.dataExtend = 'false'
        this.form.formTypeName = 'datetime'
      } else if (type == 'dic_1') { // 下拉单选
        this.form.basicJavaType = 'string'
        this.form.dataExtend = 'false'
        this.form.formTypeName = 'selectsingle'
      } else if (type == 'dic_2') { // 下拉多选
        this.form.basicJavaType = 'string'
        this.form.dataExtend = 'false'
        this.form.formTypeName = 'selectmulti'
      } else if (type == 'dic_3') { // 树单选
        this.form.basicJavaType = 'string'
        this.form.dataExtend = 'false'
        this.form.formTypeName = 'selectztree'
      } else if (type == 'dic_4') { // 树多选(含父子节点)
        this.form.basicJavaType = 'string'
        this.form.dataExtend = 'false'
        this.form.formTypeName = 'selectztreemulti'
      } else if (type == 'dic_8') { // 树多选(不含父子节点)
        this.form.basicJavaType = 'string'
        this.form.dataExtend = 'false'
        this.form.formTypeName = 'selectztreecustomcheck'
      } else if (type == 'dic_6') { // 单选(radio)
        this.form.basicJavaType = 'string'
        this.form.dataExtend = 'false'
        this.form.formTypeName = 'radio'
      } else if (type == 'dic_7') { // 多选(checkbox)
        this.form.basicJavaType = 'string'
        this.form.dataExtend = 'false'
        this.form.formTypeName = 'checkbox'
      } else if (type == 'file_1') { // 普通附件
        this.form.basicJavaType = ''
        this.form.dataExtend = 'false'
        this.form.formTypeName = 'upload'
      } else if (type == 'table_1') { // 表格(复杂属性)
        this.form.basicJavaType = ''
        this.form.dataExtend = 'true'
        this.form.formTypeName = ''

        this.rules.viewType = [
          { required: true, trigger: 'blur', message: '查看方式不能为空' }
        ]
      }

      // 文件夹上传
      else if (type == 'upload_folder') {
        this.form.basicJavaType = ''
        this.form.dataExtend = 'false'
        this.form.formTypeName = 'upload_folder'
      }

      this.chDataExtend(this.form.dataExtend)
    },
    // 设置数据类型用来反显
    setDataType() {
      if (this.form.dataExtend != 'true') {
        if (this.form.basicJavaType == 'string' && this.form.formTypeName == 'input') { // 普通文本
          this.dataType = 'text_1'
        } else if (this.form.formTypeName == 'textarea') { // 多行文本
          this.dataType = 'text_2'
        } else if (this.form.formTypeName == 'richtext') { // 富文本
          this.dataType = 'text_3'
        }
        if (this.form.basicJavaType == 'int') { // 整数
          this.dataType = 'num_1'
        } else if (this.form.basicJavaType == 'double') { // 小数
          this.dataType = 'num_2'
        }
        if (this.form.formTypeName == 'date') { // 日期
          this.dataType = 'date_1'
        } else if (this.form.formTypeName == 'datetime') { // 日期时间
          this.dataType = 'date_2'
        } else if (this.form.formTypeName == 'selectsingle') { // 下拉单选
          this.dataType = 'dic_1'
        } else if (this.form.formTypeName == 'selectmulti') { // 下拉多选
          this.dataType = 'dic_2'
        } else if (this.form.formTypeName == 'selectztree') { // 树单选
          this.dataType = 'dic_3'
        } else if (this.form.formTypeName == 'selectztreemulti') { // 树多选(含父子节点)
          this.dataType = 'dic_4'
        } else if (this.form.formTypeName == 'selectztreecustomcheck') { // 树多选(不含父子节点)
          this.dataType = 'dic_8'
        } else if (this.form.formTypeName == 'radio') { // 单选(radio)
          this.dataType = 'dic_6'
        } else if (this.form.formTypeName == 'checkbox') { // 多选(checkbox)
          this.dataType = 'dic_7'
        } else if (this.form.formTypeName == 'upload') { // 普通附件
          this.dataType = 'file_1'
        } else if (this.form.formTypeName == 'upload_folder') { // 文件夹上传
          this.dataType = 'upload_folder'
        }
      } else if (this.form.dataExtend == 'true') { // 表格(复杂属性)
        this.dataType = 'table_1'
      }
      this.form.dataType = this.dataType
    },
    handleCheckedComp(val) {
      if (val.length > 0) {
        let s = ''
        for (let i = 0; i < val.length; i++) {
          s += s === '' ? val[i] : ',' + val[i]
        }
        this.form.componentIds = s
      } else {
        this.form.componentIds = ''
      }
    },
    chDataExtend(val) {
      this.$set(this.form, 'componentIds', [])
      this.componentList = []
      if (val == 'true') {
        if (this.complexList != null && this.complexList.length > 0) {
          this.componentList = this.complexList
        }
      } else if (val == 'false') {
        if (this.simpleList != null && this.simpleList.length > 0) {
          this.componentList = this.simpleList
        }
      } else {
        if (this.simpleList != null && this.simpleList.length > 0) {
          this.componentList = this.simpleList
        }
      }
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      if (this.modelId != null) {
        this.queryParams.modelId = this.modelId
        if (this.configFieldType != null) {
          this.queryParams.configFieldType = this.configFieldType
        }

        listSelectRefField(this.queryParams).then(response => {
          this.fieldList = response.rows
          this.total = response.total
          this.loading = false
        })
      } else {
        listField(this.queryParams).then(response => {
          this.fieldList = response.rows
          this.total = response.total
          this.loading = false
        })
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset(basicCode, sortNum) {
      this.form = {
        id: null,
        createTime: null,
        createUser: null,
        delFlag: null,
        remarks: null,
        sortNum: sortNum,
        updateTime: null,
        updateUser: null,
        hierarchy: null,
        parentId: null,
        parentIds: null,
        basicCode: basicCode,
        basicColType: null,
        basicFormula: null,
        basicJavaType: '',
        basicLength: null,
        basicName: null,
        dataExtend: 'false',
        dataGenStratgy: null,
        dataUnit: null,
        formDictType: '',
        formTypeName: 'input',
        defaultValue: null,
        formwidth: null,
        viewType: '0',
        isShow: '1',
        jsMatchWhat: null,
        jsRequired: '0',
        modelId: null,
        uploadtypeId: null,
        rowspan: null,
        frontGridId: null,
        displayNumber: null,
        isOnly: null,
        isReadOnly: '0',
        initData: null,
        isAddDelFlag: '1',
        isHighLight: null,
        imgid: null,
        parentLinkageId: '',
        attributeType: '0',
        componentId: '',
        componentIds: [],
        personNum: undefined,
        dataType: '',
        templateCode: null,
        refTableIdQte: null,
        configFieldTypeQte: null,
        qteModelIds: [],
        menuCheckStrictly: true
      }
      this.resetForm('form')
      this.dcKeys = []
      if (this.$refs.qteModel != undefined) {
        this.$refs.qteModel.setCheckedKeys([])
      }
      this.dataType = 'text_1'
      this.atDisabled = false
      this.$nextTick(() => {
        this.setFormData()
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSelectionChange (val)  {
      if (this.singleSelect) {
        const temp = val.slice(0, val.length-1);
        temp.forEach((el) => {
            this.$nextTick(() => {
              this.$refs['tableRef'].toggleRowSelection(el, false);
            });
        });
        val.splice(0, val.length-1);
      }
      this.single = val.length !== 1
      this.multiple = !val.length
      this.ids = val.map(item => item.id)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.id = ''
      this.dcKeys = []

      getCodeSortNum().then(data => {
        const dataArr = data.split(':')
        getAttributes().then(dictList => {
          if (dictList != null) {
            this.dictList = dictList
          }
          this.reset(dataArr[0], dataArr[1])
          this.$nextTick(() => {
            this.collapseAll()

            if (this.modelId != null) {
              this.dcKeys.push(this.modelId)
            }
          })

          linkList().then(data => {
            this.selectList = data
            this.open = true
            this.title = '添加'
          })

          if (this.queryParams.attributeType != null) {
            this.form.attributeType = this.queryParams.attributeType

            if (this.queryParams.attributeType != 'all') {
              this.atDisabled = true
            }
          }
        })
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      this.id = id

      getField(id).then(response => {
        getAttributes().then(dictList => {
          if (dictList != null) {
            this.dictList = dictList
          }
          response.data.componentIds = response.data.componentIds == null ? [] : response.data.componentIds
          this.form = response.data
          if (this.form.personNum == null) {
            this.form.personNum = undefined
          }
          if (this.form.dataExtend == 'true') { // 复杂属性
            this.componentList = this.complexList
          } else {
            this.componentList = this.simpleList
          }
          // 反显数据类型
          this.setDataType()

          this.dcKeys = response.data.qteModelIds

          this.$nextTick(() => {
            this.collapseAll()
          })

          linkList(id).then(data => {
            this.selectList = data
            this.open = true
            this.title = '修改'
          })
        })
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.form.dataType = this.dataType
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.open = false
          this.loading = true

          if (!(this.form.componentIds != null && this.form.componentIds.length > 0)) {
            this.form.personNum = undefined
          }
          if (this.form.formTypeName != 'upload') {
            this.form.uploadtypeId = ''
          }
          if (this.form.id != null) {
            // 去掉
            updateField(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.getList()
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          } else {
            this.form.configFieldTypeQte = this.configFieldType
            addField(this.form).then(response => {
              this.$modal.msgSuccess('新增成功！')
              this.getList()
              this.loading = false
              try {
                this.$emit('gridReloadNoId')
              } catch (e) {

              }
            }).catch(() => {
              this.loading = false
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除数据项？').then(function() {
        return delField(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/field/export', {
        ...this.queryParams
      }, `field_${new Date().getTime()}.xlsx`)
    },
    editComplex(row) {
      this.$refs.editComplex.showDialog(row.id)
    }
  }
}
</script>

<style lang="scss" scoped>

::v-deep .el-input--small .el-input__inner{
  height: 36px;
  line-height: 36px;
}

::v-deep .single-select thead .el-table-column--selection .cell{
    display: none;
}
.attribute-wrap{
  padding: 20px;
}
</style>
